//
//  UIColor+Hex.m
//  Uang Pasti
//
//  Created by 李永彬 on 2025/8/16.
//

#import "UIColor+Hex.h"

@implementation UIColor (Hex)

+ (instancetype)colorWithHexString:(NSString *)hex alpha:(CGFloat)alpha {
    NSString *hexFormatted = [hex stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    hexFormatted = [hexFormatted uppercaseString];
    
    if ([hexFormatted hasPrefix:@"#"]) {
        hexFormatted = [hexFormatted substringFromIndex:1];
    }
    
    NSAssert(hexFormatted.length == 6, @"Invalid hex code used.");
    
    NSScanner *scanner = [NSScanner scannerWithString:hexFormatted];
    unsigned int rgbValue = 0;
    [scanner scanHexInt:&rgbValue];
    
    return [UIColor colorWithRed: ((CGFloat)((rgbValue & 0xFF0000) >> 16)) / 255.0
                           green: ((CGFloat)((rgbValue & 0x00FF00) >> 8)) / 255.0
                            blue: ((CGFloat)(rgbValue & 0x0000FF)) / 255.0
                           alpha: alpha];
}

+ (instancetype)colorWithHexString:(NSString *)hex {
    return [self colorWithHexString:hex alpha:1.0f];
}

@end
